<template>
    <div class="box-card box-minheight">
        <div class="card-header">
            <span>{{ curRouteName }}</span>
        </div>
        <div class="box-content">
            <el-form :inline="true" :model="searchForm" ref="searchFormRef">
                <el-form-item label="分类名称">
                    <el-select v-model="searchForm.className" placeholder="请选择分类名称" clearable filterable>
                        <el-option label="源" value="0" />
                        <el-option label="储" value="1" />
                        <el-option label="荷" value="2" />
                        <!-- <el-option label="电网参数" value="3" />
                        <el-option label="发电机组" value="4" />
                        <el-option label="负荷监测" value="5" />
                        <el-option label="储能设备" value="6" />
                        <el-option label="太阳能光伏" value="7" />
                        <el-option label="风力发电" value="8" />
                        <el-option label="逆变器监测" value="9" />
                        <el-option label="电表" value="10" /> -->
                    </el-select>
                </el-form-item>
                <el-form-item label="设备名称">
                    <el-select v-model="searchForm.deviceName" placeholder="请选择设备名称" clearable filterable>
                        <el-option label="1号电表" value="0" />
                        <el-option label="2号逆变器" value="1" />
                        <el-option label="3号电表" value="2" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">搜索</el-button>
                    <el-button type="primary" size="default" @click="handleReset">重置</el-button>
                </el-form-item>
            </el-form>
            <div style="margin: 10px 0px;">
                <el-button type="primary" :icon="Plus" @click="showDrawer('add')">新增</el-button>
                <el-button type="primary" :icon="Upload" @click="handleImport">导入</el-button>
                <el-button type="primary" :icon="Download" @click="handleExport">导出</el-button>
                <el-button type="danger" :icon="Delete" @click="handleBatchDelete">批量删除</el-button>
            </div>
            <el-table :data="deviceTypeData" @selection-change="selectChange" border :height="tableHeight">
                <el-table-column type="selection" align="center"></el-table-column>
                <el-table-column prop="categoryName" label="分类名称"></el-table-column>
                <el-table-column prop="deviceName" label="设备名称"></el-table-column>
                <el-table-column prop="categoryDesc" label="分类描述"></el-table-column>
                <el-table-column label="操作">
                    <template #default="{ row }">
                        <el-button type="primary" :icon="Edit" @click="showDrawer('edit', row)">编辑</el-button>
                        <el-button type="danger" :icon="Delete" @click="handleDelete(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页器 -->
            <el-pagination class="mt10" v-model:current-page="pageNo" v-model:page-size="pageSize"
                :page-sizes="[5, 7, 9, 11]" :background="true" layout="prev, pager, next, jumper,->,sizes,total"
                :total="total" @current-change="getTableData" @size-change="handler" />


        </div>
    </div>
    <el-drawer v-model="drawerVisible" :size="drawerSize">

        <template #header>
            <h4>{{ drawerTitle }}</h4>
        </template>
        <!-- 身体部分 -->
        <template #default>
            <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
                <el-form-item label="分类名称" prop="categoryName">
                    <el-input v-model="form.categoryName"></el-input>
                </el-form-item>
                <el-form-item label="设备名称" prop="deviceName">
                    <el-input v-model="form.deviceName"></el-input>
                </el-form-item>
                <el-form-item label="分类描述" prop="categoryDesc">
                    <el-input v-model="form.categoryDesc"></el-input>
                </el-form-item>
                <!-- <el-form-item>
                <el-button type="primary" @click="handleSubmit">保存</el-button>
                <el-button @click="handleCancel">取消</el-button>
            </el-form-item> -->
            </el-form>
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button type="primary" @click="handleSubmit">保存</el-button>
                <el-button @click="handleCancel">取消</el-button>
            </div>
        </template>

    </el-drawer>
</template>

<script setup lang="ts">
import { useRoute } from 'vue-router'
import { ref, computed, reactive, onMounted, onBeforeUnmount } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import {
    Edit,
    Plus,
    Upload,
    Download,
    Delete,
} from '@element-plus/icons-vue'


//获取路由对象
let $route = useRoute()
// 计算出当前路由名称
let curRouteName = computed(() => {
    return $route.matched[$route.matched.length - 1].meta.title
})
const searchFormRef = ref<FormInstance>()
const searchForm = reactive({
    className: '0',
    deviceName: '2',
})
const handleSearch = () => {
    console.log('submit!')
}
//重置按钮
const handleReset = () => {
}

interface DeviceTypeData {
    id: number;
    categoryName: string;
    deviceName: string;
    categoryDesc: string;
}
//准备一个数组存储批量删除的用户的ID
let selectIdArr = ref<DeviceTypeData[]>([]);

const deviceTypeData = ref<DeviceTypeData[]>([
    {
        id: 1,
        categoryName: '分类1',
        deviceName: '设备1',
        categoryDesc: '分类1描述',
    },
    // 可以添加更多的设备类型数据
]);

//默认页码
let pageNo = ref<number>(1);
//一页展示几条数据
let pageSize = ref<number>(5);
//用户总个数
let total = ref<number>(0);

//组件挂载完毕
onMounted(() => {
    getTableData();
    calculateTableHeight();
    window.addEventListener('resize', handleResize);
});
onBeforeUnmount(() => {
    window.removeEventListener('resize', handleResize);
})
const getTableData = async (pager = 1) => {
    //收集当前页码
    pageNo.value = pager;
    // let result: UserResponseData = await reqUserInfo(pageNo.value, pageSize.value, keyword.value);
    // if (result.code == 200) {
    //     total.value = result.data.total;
    //     userArr.value = result.data.records;
    // }
}
//分页器下拉菜单的自定义事件的回调
const handler = () => {
    getTableData();
}

const tableHeight = ref(0); // 表格高度
// 计算表格高度的函数
const calculateTableHeight = () => {
    const windowHeight = window.innerHeight - 180; // 获取窗口高度
    const tableHeaderHeight = 40; // 表格头部高度
    const tablePaginationHeight = 60; // 表格分页高度
    const padding = 20; // 上下边距
    tableHeight.value = windowHeight - tableHeaderHeight - tablePaginationHeight - padding;
};

// 监听窗口大小变化，动态计算表格高度
const handleResize = () => {
    calculateTableHeight();
};

const drawerVisible = ref(false);
const drawerTitle = ref('');
const drawerSize = ref('600');
//获取form组件实例
let formRef = ref<any>();
const form = reactive<DeviceTypeData>({
    id: 0,
    categoryName: '',
    deviceName: '',
    categoryDesc: '',
});
const rules = reactive<FormRules<DeviceTypeData>>({
    categoryName: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
    deviceName: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
    // categoryDesc: [{ required: true, message: '请输入分类描述', trigger: 'blur' }],
});

function showDrawer(type: 'add' | 'edit', row?: DeviceTypeData) {
    if (type === 'add') {
        drawerTitle.value = '新增设备类型';
        form.id = 0;
        form.categoryName = '';
        form.deviceName = '';
        form.categoryDesc = '';
    } else if (type === 'edit' && row) {
        drawerTitle.value = '编辑设备类型';
        form.id = row.id;
        form.categoryName = row.categoryName;
        form.deviceName = row.deviceName;
        form.categoryDesc = row.categoryDesc;
    }
    drawerVisible.value = true;
}

const handleSubmit = () => {
    (formRef.value as any).validate((valid: boolean) => {
        if (valid) {
            if (form.id === 0) {
                // 新增设备类型
                const newDeviceType: DeviceTypeData = {
                    id: deviceTypeData.value.length + 1,
                    categoryName: form.categoryName,
                    deviceName: form.deviceName,
                    categoryDesc: form.categoryDesc,
                };
                deviceTypeData.value.push(newDeviceType);
                ElMessage({
                    message: '新增成功！',
                    type: 'success',
                })
            } else {
                // 编辑设备类型
                const index = deviceTypeData.value.findIndex((item) => item.id === form.id);
                if (index !== -1) {
                    deviceTypeData.value[index].categoryName = form.categoryName;
                    deviceTypeData.value[index].deviceName = form.deviceName;
                    deviceTypeData.value[index].categoryDesc = form.categoryDesc;
                    ElMessage({
                        message: '编辑成功',
                        type: 'success',
                    })
                }
            }
            drawerVisible.value = false;
        } else {
            return false;
        }
    });
}

function handleCancel() {
    drawerVisible.value = false;
}

function handleDelete(row: DeviceTypeData) {
    const index = deviceTypeData.value.findIndex((item) => item.id === row.id);
    if (index !== -1) {
        deviceTypeData.value.splice(index, 1);
        ElMessage.success('删除成功');
    }
}

//table复选框勾选的时候会触发的事件
const selectChange = (value: any) => {
    selectIdArr.value = value;
}

function handleBatchDelete() {
    if (selectIdArr.value.length === 0) {
        ElMessage.warning('请先选择要删除的设备');
        return;
    }
    const ids = selectIdArr.value.map((item: DeviceTypeData) => item.id);
    deviceTypeData.value = deviceTypeData.value.filter((item) => !ids.includes(item.id));
    ElMessage.success('删除成功');
}

const handleImport = () => {
    // 处理导入逻辑
}

const handleExport = () => {
    // 处理导出逻辑
}

</script>

<style scoped lang="scss">
.demo-tabs>.el-tabs__content {
    padding: 32px;
    color: #6b778c;
    font-size: 32px;
    font-weight: 600;
}

.el-tabs--right .el-tabs__content,
.el-tabs--left .el-tabs__content {
    height: 100%;
}
</style>